package com.kingsoft.demo.xml.dom;

import java.io.File;
import java.io.FileWriter;
import java.io.PrintWriter;
import java.io.StringWriter;

import javax.xml.transform.dom.DOMResult;

import org.w3c.dom.Document;
import org.w3c.dom.Node;

import com.sun.org.apache.xml.internal.serialize.OutputFormat;
import com.sun.org.apache.xml.internal.serialize.XMLSerializer;

public class TestXml {
	
	
	/**
	 * 格式化输出XML
	 * @param document
	 * @param filePath
	 */
	private static void doc2XmlFile(Document	document, String filePath) {
		  try {
			    
		   OutputFormat format = new OutputFormat(document);//Serialize DOM
		     format.setEncoding("UTF-8");
		     StringWriter stringOut = new StringWriter();//Writer will be a String
		     XMLSerializer serial = new XMLSerializer(stringOut, format);
		     serial.asDOMSerializer();// As a DOM Serializer
		     serial.serialize(document.getDocumentElement());
		     String STRXML = stringOut.toString(); //Spit out DOM as a String
		     File f = new File(filePath);
		     PrintWriter out = new PrintWriter(new FileWriter(f));
		     out.print(STRXML + "/n");
		     out.close();
		  } catch (Exception ex) {
		   ex.printStackTrace();
		  }
	}
	
	public static void main(String[] args) {
		
		DOMResult domResult = new DOMResult();
		Node returnNode = domResult.getNode();	
		
		doc2XmlFile((Document)returnNode, "E:/11.xml");
		
	}
	


}
